from django.shortcuts import render
import json
from django import http
import pymysql


def login_check(request):
    users = "未接收"
    pw = "未接收"

    if 'users' in request.GET and request.GET['users']:
        users = request.GET['users']
    if 'pw' in request.GET and request.GET['pw']:
        pw = request.GET['pw']

    db = db_connect()
    cursor = db.cursor()
    sql = "SELECT * FROM t_users WHERE users='" + users + "' AND pw='" + pw + "'"

    if cursor.execute(sql):
        data = cursor.fetchone()
        id = data[0]
        wx = data[3]
        arr = [id, wx]
        cursor.close()
        db.close()
        return http.HttpResponse(json.dumps(arr, ensure_ascii=False))
    else:
        cursor.close()
        db.close()
        return http.HttpResponse("no")


# 创建连接数据库
def db_connect():
    db = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        db='mp'
    )
    return db


# 注册 添加数据
def register(request):
    users = ""
    pw = ""
    wx = ""
    pn = ""
    add1 = ""
    add2 = ""

    if 'users' in request.GET and request.GET['users']:
        users = request.GET['users']
    if 'pw' in request.GET and request.GET['pw']:
        pw = request.GET['pw']
    if 'wx' in request.GET and request.GET['wx']:
        wx = request.GET['wx']
    if 'pn' in request.GET and request.GET['pn']:
        pn = request.GET['pn']
    if 'add1' in request.GET and request.GET['add1']:
        add1 = request.GET['add1']
    if 'add2' in request.GET and request.GET['add2']:
        add2 = request.GET['add2']

    # add1_list = json.loads(add1)
    t_add = "".join(eval(add1)) + add2

    db = db_connect()
    cursor = db.cursor()
    sql = "INSERT INTO t_users(users,pw,wx,pn,t_add) VALUES('"+users+"','"+pw+"','"+wx+"','"+pn+"','"+t_add+"')"

    if cursor.execute(sql):
        cursor.close()
        db.close()
        return http.HttpResponse("yes")
    else:
        cursor.close()
        db.close()
        return http.HttpResponse("no")
